<template>
	<view class="container">
		<!-- 用户信息头部 -->
		<view class="user-header">
			<view v-if="userInfo" class="user-info">
				<image :src="userInfo.avatar || '/static/images/default-avatar.png'" class="avatar" mode="aspectFill" />
				<view class="user-details">
					<text class="username">{{ userInfo.nickname }}</text>
					<text class="user-level">{{ userInfo.leve || '普通会员' }}</text>
				</view>
				<view class="edit-btn" @click="editProfile">
					<text class="edit-icon">✏️</text>
				</view>
			</view>
			<view v-else class="login-prompt">
				<image src="/static/images/default-avatar.png" class="avatar" mode="aspectFill" />
				<view class="login-text">
					<text class="login-title">立即登录</text>
					<text class="login-desc">享受更多优惠</text>
				</view>
				<button class="login-btn" @click="goToLogin">登录</button>
			</view>
		</view>

		<!-- 用户数据统计 -->
		<view v-if="userInfo" class="user-stats">
			<view class="stat-item" @click="goToOrders">
				<text class="stat-number">{{ orderCount }}</text>
				<text class="stat-label">我的订单</text>
			</view>
			<view class="stat-item" @click="goToFavorites">
				<text class="stat-number">{{ favoriteCount }}</text>
				<text class="stat-label">我的收藏</text>
			</view>
			<view class="stat-item" @click="goToPoints">
				<text class="stat-number">{{ userPoints.points }}</text>
				<text class="stat-label">积分</text>
			</view>
			<view class="stat-item" @click="goToCoupons">
				<text class="stat-number">{{ couponCount }}</text>
				<text class="stat-label">优惠券</text>
			</view>
		</view>

		<!-- 功能菜单 -->
		<view class="menu-section">
			<view class="menu-group">
				<view class="menu-item" @click="goToOrders">
					<view class="menu-icon">📦</view>
					<text class="menu-title">我的订单</text>
					<text class="menu-arrow">></text>
				</view>
				<view class="menu-item" @click="goToAddresses">
					<view class="menu-icon">📍</view>
					<text class="menu-title">收货地址</text>
					<text class="menu-arrow">></text>
				</view>
				<view class="menu-item" @click="goToFavorites">
					<view class="menu-icon">❤️</view>
					<text class="menu-title">我的收藏</text>
					<text class="menu-arrow">></text>
				</view>
			</view>

			<view class="menu-group">
				<view class="menu-item" @click="goToPoints">
					<view class="menu-icon">🎁</view>
					<text class="menu-title">积分商城</text>
					<text class="menu-arrow">></text>
				</view>
				<view class="menu-item" @click="goToCoupons">
					<view class="menu-icon">🎫</view>
					<text class="menu-title">优惠券</text>
					<text class="menu-arrow">></text>
				</view>
				<view class="menu-item" @click="goToCustomerService">
					<view class="menu-icon">💬</view>
					<text class="menu-title">客服中心</text>
					<text class="menu-arrow">></text>
				</view>
			</view>

			<view class="menu-group">
				<view class="menu-item" @click="goToSettings">
					<view class="menu-icon">⚙️</view>
					<text class="menu-title">设置</text>
					<text class="menu-arrow">></text>
				</view>
				<view class="menu-item" @click="goToAbout">
					<view class="menu-icon">ℹ️</view>
					<text class="menu-title">关于我们</text>
					<text class="menu-arrow">></text>
				</view>
			</view>
		</view>

		<!-- 退出登录 -->
		<view v-if="userInfo" class="logout-section">
			<button class="logout-btn" @click="logout">退出登录</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		userApi,
		orderApi,
		favoriteApi,
		couponApi
	} from '@/api/index.js';
	import common from '@/utils/common.js';
	import storage from '@/utils/storage.js';
	import {
		onShow
	} from '@dcloudio/uni-app';

	// 响应式数据
	const userInfo = ref(null);
	const orderCount = ref(0);
	const favoriteCount = ref(0);
	const couponCount = ref(0);
	const userPoints = ref(0);

	// 加载用户信息
	const loadUserInfo = async () => {
		const token = storage.getToken();
		if (!token) {
			userInfo.value = null;
			return Promise.resolve(null);
		}

		// 从后端获取最新用户信息
		try {
			const res = await userApi.getUserInfo();
			if (res.code === 200 && res.data) {
				userInfo.value = res.data;
				// 更新本地缓存
				storage.setUserInfo(res.data);
				return Promise.resolve(res.data);
			} else {
				console.warn('获取用户信息接口返回非成功状态码或无数据:', res);
				storage.clearUserData();
				userInfo.value = null;
				// 如果获取失败，尝试跳转登录
				uni.navigateTo({
					url: '/pages/login/login'
				});
				return Promise.reject(new Error('获取用户信息失败')); // 返回被拒绝的Promise
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			// token可能过期或网络错误，清除本地数据
			storage.clearUserData();
			userInfo.value = null;
			// 错误时跳转登录
			uni.navigateTo({
				url: '/pages/login/login'
			});
			return Promise.reject(error); // 返回被拒绝的Promise
		}
	};

	// 加载用户统计数据
	const loadUserStats = async () => {
		if (!userInfo.value) {
			return;
		}


		try {
			// 获取订单数量
			const orderRes = await orderApi.getOrderStats();
			if (orderRes.code === 200) {
				orderCount.value = orderRes.data && orderRes.data.total !== undefined ? orderRes.data.total : 0;
			} else {
				console.warn('获取订单统计失败:', orderRes.message);
			}

			// 获取收藏数量
			const favoriteRes = await favoriteApi.getFavoriteCount();
			if (favoriteRes.code === 200) {
				// 直接使用返回的data作为收藏数量
				favoriteCount.value = favoriteRes.data;
			} else {
				console.warn('获取收藏数量失败:', favoriteRes.message);
			}

			// 获取用户积分
			try {
				const pointsRes = await userApi.getUserPoints();
				if (pointsRes.code === 200 && pointsRes.data) {
					userPoints.value = pointsRes.data || null;
					userInfo.value.leve = fromLeve(userPoints.value.memberLevel);
				} else {
					console.warn('获取用户积分失败:', pointsRes.msg);
					userPoints.value = 0;
				}
			} catch (error) {
				console.error('获取用户积分出错:', error);
				userPoints.value = 0;
			}

			// 获取用户优惠券数量
			try {
				const couponRes = await couponApi.getUserCoupons();
				if (couponRes.code === 200 && couponRes.data) {
					couponCount.value = couponRes.data.length || 0;
				} else {
					console.warn('获取用户优惠券失败:', couponRes.msg);
					couponCount.value = 0;
				}
			} catch (error) {
				console.error('获取用户优惠券出错:', error);
				couponCount.value = 0;
			}

		} catch (error) {
			console.error('获取统计数据失败:', error);
			// 统计数据失败不影响用户信息显示，但可以记录日志
		}
	};

	// 跳转到登录页
	const goToLogin = () => {
		uni.navigateTo({
			url: '/pages/login/login'
		});
	};

	// 编辑资料
	const editProfile = () => {
		uni.navigateTo({
			url: '/pages/user/profile'
		});
	};

	// 跳转到订单页面
	const goToOrders = () => {
		if (!userInfo.value) {
			goToLogin();
			return;
		}
		uni.navigateTo({
			url: '/pages/order/list'
		});
	};

	// 跳转到地址页面
	const goToAddresses = () => {
		if (!userInfo.value) {
			goToLogin();
			return;
		}
		uni.navigateTo({
			url: '/pages/address/list'
		});
	};

	// 跳转到收藏页面
	const goToFavorites = () => {
		if (!userInfo.value) {
			goToLogin();
			return;
		}
		uni.navigateTo({
			url: '/pages/favorite/favorite'
		});
	};

	// 跳转到积分页面
	const goToPoints = () => {
		if (!userInfo.value) {
			goToLogin();
			return;
		}
		uni.navigateTo({
			url: '/pages/points/points'
		});
	};

	// 跳转到优惠券页面
	const goToCoupons = () => {
		if (!userInfo.value) {
			goToLogin();
			return;
		}
		uni.navigateTo({
			url: '/pages/coupon/coupon'
		});
	};

	// 跳转到客服页面
	const goToCustomerService = () => {
		uni.navigateTo({
			url: '/pages/service/service'
		});
	};

	// 跳转到设置页面
	const goToSettings = () => {
		if (!userInfo.value) {
			goToLogin();
			return;
		}
		uni.navigateTo({
			url: '/pages/settings/settings'
		});
	};

	// 跳转到关于页面
	const goToAbout = () => {
		uni.navigateTo({
			url: '/pages/about/about'
		});
	};

	// 退出登录
	const logout = async () => {
		const confirmed = await common.showConfirm('确定要退出登录吗？');
		if (!confirmed) return;

		try {
			await userApi.logout();
			storage.clearUserData();
			userInfo.value = null;
			common.showSuccess('退出成功');

			// 跳转到首页
			uni.switchTab({
				url: '/pages/index/index'
			});
		} catch (error) {
			console.error('退出登录失败:', error);
			// 即使API调用失败，也清除本地数据
			storage.clearUserData();
			userInfo.value = null;
			common.showSuccess('退出成功');
		}
	};

	const fromLeve = (status)  => {
		return status === 1 ? "普通会员" : status === 2 ?
			"银卡会员" : status === 3 ? "金卡会员" : "钻石会员"
	}

	// 页面显示时加载数据
	onShow(async () => {
		console.log('user.vue onShow: 页面显示');
		// 先加载用户信息，确保加载完成后再加载统计数据
		try {
			await loadUserInfo();
			// 只有在成功加载用户信息后才加载统计数据
			if (userInfo.value) {
				await loadUserStats();
			}
		} catch (error) {
			console.error('加载数据出错:', error);
		}
	});
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background: #f5f5f5;
	}

	.user-header {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding: 60rpx 40rpx 40rpx;
		color: #fff;
	}

	.user-info {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		border: 4rpx solid rgba(255, 255, 255, 0.3);
		margin-right: 30rpx;
	}

	.user-details {
		flex: 1;
	}

	.username {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
	}

	.user-level {
		font-size: 26rpx;
		opacity: 0.8;
	}

	.edit-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.edit-icon {
		font-size: 32rpx;
	}

	.login-prompt {
		display: flex;
		align-items: center;
	}

	.login-text {
		flex: 1;
		margin-left: 30rpx;
	}

	.login-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
	}

	.login-desc {
		font-size: 26rpx;
		opacity: 0.8;
	}

	.login-btn {
		background: rgba(255, 255, 255, 0.2);
		color: #fff;
		border: 2rpx solid rgba(255, 255, 255, 0.3);
		border-radius: 25rpx;
		padding: 15rpx 30rpx;
		font-size: 26rpx;
	}

	.user-stats {
		background: #fff;
		margin: -20rpx 20rpx 20rpx;
		border-radius: 12rpx;
		padding: 30rpx;
		display: flex;
		justify-content: space-around;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.stat-item {
		text-align: center;
	}

	.stat-number {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.stat-label {
		font-size: 24rpx;
		color: #666;
	}

	.menu-section {
		padding: 0 20rpx;
	}

	.menu-group {
		background: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
	}

	.menu-item {
		display: flex;
		align-items: center;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.menu-item:last-child {
		border-bottom: none;
	}

	.menu-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		margin-right: 20rpx;
	}

	.menu-title {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.menu-arrow {
		font-size: 24rpx;
		color: #ccc;
	}

	.logout-section {
		padding: 40rpx 20rpx;
	}

	.logout-btn {
		width: 100%;
		background: #ff4757;
		color: #fff;
		border: none;
		border-radius: 12rpx;
		padding: 25rpx;
		font-size: 28rpx;
	}
</style>